package core;

import java.io.File;
import java.io.FileInputStream;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;

import core.ISpeaker;
import core.IMessenger;
import core.Client;

public class Speaker implements ISpeaker
{
	protected IMessenger messenger;
	public Speaker()
	{

	}
	
	public void setMessenger(IMessenger messenger)
	{
		this.messenger = messenger;
	}
	
	public void messageRecived(Contact contact, String message)
	{
		if (messenger != null)
		{
			//System.out.print(message.substring(0,1));
			if (message.substring(0,1).contains("M") || message.substring(0,1).contains("m"))
			{
				messenger.messageReceived(contact, message.substring(1));
			}
			else if (message.substring(0,1).contains("F") || message.substring(0,1).contains("f"))
			{
				int nameLength = Integer.parseInt(message.substring(1,4));
				String name = message.substring(4, 4+nameLength);
				try
				{
					byte[] body = new BASE64Decoder().decodeBuffer(message.substring(4+nameLength));
					messenger.fileReceived(contact, name, body);
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		}
	}
	
	public void sendMessage(Contact contact, String message)
	{
		Client.instance().send(contact, "M"+message);
	}
	
	public void sendFile(Contact contact, String name, byte[] data)
	{
		// File f = new File(path);
		// if (f.exists() && f.isFile())
		// {
			// String name = f.getName();
			// try
			// {
				// FileInputStream in = new FileInputStream(f);
				// byte[] data;
				String body;
				// if (in.available() > 0)
				// {
					// data = new byte[in.available()];
					// in.read(data);
                if (data != null)
                {
                    body = new BASE64Encoder().encode(data);
					Client.instance().send(contact, String.format("F%03d%s%s",name.length(), name, body));
                }
                else
                    Client.instance().send(contact, String.format("F%03d%s",name.length(),name));
				// }
				// else
				// {
					// Client.instance().send(contact, String.format("F%03d%s",name.length(),name));
				// }
			// }
			// catch (Exception e)
			// {
				// e.printStackTrace();
			// }
		// }
	}
}